package com.meirengu.webview.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.MD5Util;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.model.KwXbbPush;
import com.meirengu.webview.model.KwXbbPushLog;
import com.meirengu.webview.service.KwXbbPushLogService;
import com.meirengu.webview.service.KwXbbPushService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * KwXbbPush服务实现层
 *
 * @author Mao
 * @create Fri May 04 15:39:30 CST 2018
 */
@Service
public class KwXbbPushServiceImpl extends BaseServiceImpl<KwXbbPush> implements KwXbbPushService {


    Logger logger = LoggerFactory.getLogger(KwXbbPushServiceImpl.class);


    @Autowired
    private KwXbbPushLogService kwXbbPushLogService;

    /**
     * @param
     * @return
     */
    public Integer applyInsurance(String policyHolderName, String mobile, String policyHolderBirth,
                                  String policyHolderSex, String fromIp, String loanAmount, String income,
                                  String hasHouse, String hasCar, String isCommercialInsurance,
                                  String userAgent, String idCard) throws Exception {

        String adCode = ConfigUtil.getConfig("xbb.adcode");
        String signStr = ConfigUtil.getConfig("xbb.signstr");
        String url = ConfigUtil.getConfig("xbb.url");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("adCode", adCode);
        jsonObject.put("policyHolderName", policyHolderName);
        jsonObject.put("mobile", mobile);
        jsonObject.put("policyHolderBirth", policyHolderBirth);
        jsonObject.put("policyHolderSex", policyHolderSex);
        jsonObject.put("insuredPersonName", policyHolderName);
        jsonObject.put("insuredPersonBirth", policyHolderBirth);
        jsonObject.put("insuredPersonSex", policyHolderSex);
        jsonObject.put("relation", "SELF");
        jsonObject.put("activityConfigNum", "0");
        jsonObject.put("sign", MD5Util.get32MD5(adCode + signStr + mobile));
        jsonObject.put("fromIp", fromIp);
        jsonObject.put("userAgent", userAgent);
        jsonObject.put("policyHolderIdCard", idCard);
        JSONObject tagJson = new JSONObject();
        //tagJson.put("loanAmount",loanAmount);
        tagJson.put("income", income);
        //tagJson.put("hasHouse",hasHouse);
        //tagJson.put("hasCar",hasCar);
        tagJson.put("isCommercialInsurance", isCommercialInsurance);
        jsonObject.put("tag", tagJson);


        //接口调用信息表
        KwXbbPush kwXbbPush = new KwXbbPush();
        kwXbbPush.setInterfaceCode("xbb");
        kwXbbPush.setInterfaceName("新贝");
        kwXbbPush.setMobile(mobile);
        kwXbbPush.setCode(Constants.BUSINESS_STATUS_FAIL);


        KwXbbPushLog kwXbbPushLog = new KwXbbPushLog();
        kwXbbPushLog.setInterfaceCode("xbb");
        kwXbbPushLog.setInterfaceName("新贝");
        kwXbbPushLog.setMobile(mobile);
        kwXbbPushLog.setSendUrl(url.toString());
        kwXbbPushLog.setParams(jsonObject.toString());


        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPost(url, jsonObject.toString());
            int code = hr.getStatusCode();
            if (code == 200) {
                kwXbbPushLog.setBackUrl(hr.toString());
                kwXbbPushLog.setHttpCode(200);
                kwXbbPushLog.setHttpContent(hr.toString());

                logger.info("==KwXbbPushServiceImpl.applyLoan request success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String rCode = returnMsg.getString("status");
                String rMsg = returnMsg.getString("message");
                if ("SUCCEEDED".equals(rCode)) {
                    kwXbbPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                    JSONArray arr = returnMsg.getJSONArray("detailMessage");
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject json = arr.getJSONObject(i);
                        String status = json.getString("status");
                        if ("SUCCEEDED".equals(status)) {
                            kwXbbPush.setMessage(json.getString("companyName") + ":" + json.getString("productName"));
                        }
                    }
                    logger.info("==KwXbbPushServiceImpl.applyLoan business success");
                } else {
                    kwXbbPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                    kwXbbPush.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                    logger.warn("==KwXbbPushServiceImpl.applyLoan business fail");
                }
            } else {
                kwXbbPushLog.setBackUrl(hr.toString());
                kwXbbPushLog.setHttpCode(code);
                kwXbbPushLog.setHttpContent(hr.toString());
                logger.warn("==KwXbbPushServiceImpl.applyLoan request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwXbbPushLog.setHttpCode(408);
            kwXbbPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            insert(kwXbbPush);
            kwXbbPushLog.setPushId(kwXbbPush.getId());
            kwXbbPushLogService.insert(kwXbbPushLog);
            return kwXbbPush.getCode();
        }

    }

    /**
     * xbb发送平安保险
     *
     * @param policyHolderName
     * @param mobile
     * @param policyHolderBirth
     * @param policyHolderSex
     * @param fromIp
     * @param loanAmount
     * @param income
     * @param hasHouse
     * @param hasCar
     * @param isCommercialInsurance
     * @param userAgent
     * @return
     * @throws Exception
     */
    @Override
    public Integer applyInsurance2(String policyHolderName, String mobile, String policyHolderBirth, String policyHolderSex, String fromIp, String loanAmount, String income, String hasHouse, String hasCar, String isCommercialInsurance, String userAgent, String idCard) throws Exception {
        String adCode = ConfigUtil.getConfig("xbb2.adcode");
        String signStr = ConfigUtil.getConfig("xbb2.key");
        String url = ConfigUtil.getConfig("xbb2.url");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("adCode", adCode);
        jsonObject.put("policyHolderName", policyHolderName);
        jsonObject.put("mobile", mobile);
        jsonObject.put("policyHolderBirth", policyHolderBirth);
        jsonObject.put("policyHolderSex", policyHolderSex);
        jsonObject.put("insuredPersonName", policyHolderName);
        jsonObject.put("insuredPersonBirth", policyHolderBirth);
        jsonObject.put("insuredPersonSex", policyHolderSex);
        jsonObject.put("relation", "SELF");
        jsonObject.put("activityConfigNum", "0");
        jsonObject.put("sign", MD5Util.get32MD5(adCode + signStr + mobile).toLowerCase());
        jsonObject.put("fromIp", fromIp);
        jsonObject.put("userAgent", userAgent);
        jsonObject.put("policyHolderIdCard", idCard);
        JSONObject tagJson = new JSONObject();
        tagJson.put("loanAmount", loanAmount);
        tagJson.put("income", income);
        //tagJson.put("hasHouse",hasHouse);
        //tagJson.put("hasCar",hasCar);
        tagJson.put("isCommercialInsurance", isCommercialInsurance);
        tagJson.put("hasCreditCard", "有");
        jsonObject.put("tag", tagJson);


        //接口调用信息表
        KwXbbPush kwXbbPush = new KwXbbPush();
        kwXbbPush.setInterfaceCode("xbb2");
        kwXbbPush.setInterfaceName("新贝2");
        kwXbbPush.setMobile(mobile);
        kwXbbPush.setCode(Constants.BUSINESS_STATUS_FAIL);


        KwXbbPushLog kwXbbPushLog = new KwXbbPushLog();
        kwXbbPushLog.setInterfaceCode("xbb2");
        kwXbbPushLog.setInterfaceName("新贝2");
        kwXbbPushLog.setMobile(mobile);
        kwXbbPushLog.setSendUrl(url.toString());
        kwXbbPushLog.setParams(jsonObject.toString());


        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPost(url, jsonObject.toString());
            int code = hr.getStatusCode();
            if (code == 200) {
                kwXbbPushLog.setBackUrl(hr.toString());
                kwXbbPushLog.setHttpCode(200);
                kwXbbPushLog.setHttpContent(hr.toString());

                logger.info("==KwXbbPushServiceImpl.applyLoan2 request success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String rCode = returnMsg.getString("status");
                String rMsg = returnMsg.getString("message");
                if ("SUCCEEDED".equals(rCode)) {
                    kwXbbPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                    JSONArray arr = returnMsg.getJSONArray("detailMessage");
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject json = arr.getJSONObject(i);
                        String status = json.getString("status");
                        if ("SUCCEEDED".equals(status)) {
                            kwXbbPush.setMessage(json.getString("companyName") + ":" + json.getString("productName"));
                        }
                    }
                    logger.info("==KwXbbPushServiceImpl.applyLoan2 business success");
                } else {
                    kwXbbPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                    kwXbbPush.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                    logger.warn("==KwXbbPushServiceImpl.applyLoan2 business fail");
                }
            } else {
                kwXbbPushLog.setBackUrl(hr.toString());
                kwXbbPushLog.setHttpCode(code);
                kwXbbPushLog.setHttpContent(hr.toString());
                logger.warn("==KwXbbPushServiceImpl.applyLoan2 request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwXbbPushLog.setHttpCode(408);
            kwXbbPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            insert(kwXbbPush);
            kwXbbPushLog.setPushId(kwXbbPush.getId());
            kwXbbPushLogService.insert(kwXbbPushLog);
            return kwXbbPush.getCode();
        }
    }

    /**
     * @param
     * @return
     */
    public Integer applyInsurance3(String policyHolderName, String mobile, String policyHolderBirth,
                                   String policyHolderSex, String fromIp, String loanAmount, String income, String fund,
                                   String hasHouse, String hasCar, String isCommercialInsurance, String userAgent, String idCard) throws Exception {

        String adCode = ConfigUtil.getConfig("xbb3.adcode");
        String signStr = ConfigUtil.getConfig("xbb3.key");
        /*xbb4传非平安有身份证的*/
        if (StringUtils.isNotBlank(idCard)) {
            adCode = ConfigUtil.getConfig("xbb4.adcode");
            signStr = ConfigUtil.getConfig("xbb4.key");
        }
        String url = ConfigUtil.getConfig("xbb3.url");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("adCode", adCode);
        jsonObject.put("policyHolderName", policyHolderName);
        jsonObject.put("mobile", mobile);
        jsonObject.put("policyHolderBirth", policyHolderBirth);
        jsonObject.put("policyHolderSex", policyHolderSex);
        jsonObject.put("insuredPersonName", policyHolderName);
        jsonObject.put("insuredPersonBirth", policyHolderBirth);
        jsonObject.put("insuredPersonSex", policyHolderSex);
        jsonObject.put("policyHolderIdCard", idCard);
        jsonObject.put("relation", "SELF");
        jsonObject.put("activityConfigNum", "0");
        jsonObject.put("sign", MD5Util.get32MD5(adCode + signStr + mobile));
        jsonObject.put("fromIp", fromIp);
        jsonObject.put("userAgent", userAgent);
        JSONObject tagJson = new JSONObject();
        //tagJson.put("loanAmount",loanAmount);
        tagJson.put("income", income);
        tagJson.put("localProvidentFund", fund);
        //tagJson.put("hasHouse",hasHouse);
        //tagJson.put("hasCar",hasCar);
        tagJson.put("isCommercialInsurance", isCommercialInsurance);
        jsonObject.put("tag", tagJson);


        //接口调用信息表
        KwXbbPush kwXbbPush = new KwXbbPush();
        kwXbbPush.setInterfaceCode("xbb3");
        kwXbbPush.setInterfaceName("新贝3");
        kwXbbPush.setMobile(mobile);
        kwXbbPush.setCode(Constants.BUSINESS_STATUS_FAIL);


        KwXbbPushLog kwXbbPushLog = new KwXbbPushLog();
        kwXbbPushLog.setInterfaceCode("xbb3");
        kwXbbPushLog.setInterfaceName("新贝3");
        kwXbbPushLog.setMobile(mobile);
        kwXbbPushLog.setSendUrl(url.toString());
        kwXbbPushLog.setParams(jsonObject.toString());


        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPost(url, jsonObject.toString());
            int code = hr.getStatusCode();
            if (code == 200) {
                kwXbbPushLog.setBackUrl(hr.toString());
                kwXbbPushLog.setHttpCode(200);
                kwXbbPushLog.setHttpContent(hr.toString());

                logger.info("==KwXbbPushServiceImpl.applyLoan3 request success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String rCode = returnMsg.getString("status");
                String rMsg = returnMsg.getString("message");
                if ("SUCCEEDED".equals(rCode)) {
                    kwXbbPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                    JSONArray arr = returnMsg.getJSONArray("detailMessage");
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject json = arr.getJSONObject(i);
                        String status = json.getString("status");
                        if ("SUCCEEDED".equals(status)) {
                            kwXbbPush.setMessage(json.getString("companyName") + ":" + json.getString("productName"));
                        }
                    }
                    logger.info("==KwXbbPushServiceImpl.applyLoan3 business success");
                } else {
                    kwXbbPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                    kwXbbPush.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                    logger.warn("==KwXbbPushServiceImpl.applyLoan3 business fail");
                }
            } else {
                kwXbbPushLog.setBackUrl(hr.toString());
                kwXbbPushLog.setHttpCode(code);
                kwXbbPushLog.setHttpContent(hr.toString());
                logger.warn("==KwXbbPushServiceImpl.applyLoan3 request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwXbbPushLog.setHttpCode(408);
            kwXbbPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            insert(kwXbbPush);
            kwXbbPushLog.setPushId(kwXbbPush.getId());
            kwXbbPushLogService.insert(kwXbbPushLog);
            return kwXbbPush.getCode();
        }

    }

}
